<template>
  <div class="category-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>应用分类</span>
          <el-button type="primary" @click="handleAdd">新增分类</el-button>
        </div>
      </template>

      <!-- 分类列表 -->
      <el-table v-loading="loading" :data="categoryList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" min-width="150" />
        <el-table-column prop="code" label="分类编码" width="150" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="sort" label="排序" width="100" sortable />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <!-- 分类表单对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        destroy-on-close
      >
        <el-form
          ref="categoryFormRef"
          :model="categoryForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="分类编码" prop="code">
            <el-input v-model="categoryForm.code" placeholder="请输入分类编码" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="categoryForm.description"
              type="textarea"
              placeholder="请输入描述"
            />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="categoryForm.sort" :min="0" :max="999" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="categoryForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
});

// 表单引用
const categoryFormRef = ref<FormInstance>();

// 数据列表
const loading = ref(false);
const categoryList = ref<any[]>([]);
const total = ref(0);

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const categoryForm = reactive({
  id: 0,
  name: '',
  code: '',
  description: '',
  sort: 0,
  status: 1
});

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { pattern: /^[a-z0-9_]+$/, message: '只能包含小写字母、数字和下划线', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
};

// 获取分类列表
const fetchCategoryList = () => {
  loading.value = true;
  
  // 模拟数据，实际项目中应该从API获取
  setTimeout(() => {
    const mockData = [];
    for (let i = 1; i <= 10; i++) {
      mockData.push({
        id: i,
        name: `分类${i}`,
        code: `category_${i}`,
        description: `这是分类${i}的描述信息`,
        sort: i * 10,
        status: i % 2,
        createTime: new Date(Date.now() - i * 86400000).toLocaleString()
      });
    }
    
    categoryList.value = mockData;
    total.value = 10;
    loading.value = false;
  }, 500);
};

// 新增分类
const handleAdd = () => {
  resetForm();
  dialogTitle.value = '新增分类';
  dialogVisible.value = true;
};

// 编辑分类
const handleEdit = (row: any) => {
  resetForm();
  dialogTitle.value = '编辑分类';
  Object.assign(categoryForm, row);
  dialogVisible.value = true;
};

// 删除分类
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该分类吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success('删除成功');
      
      // 从列表中移除
      const index = categoryList.value.findIndex(item => item.id === row.id);
      if (index !== -1) {
        categoryList.value.splice(index, 1);
        total.value--;
      }
    }, 500);
  }).catch(() => {});
};

// 状态变更
const handleStatusChange = (row: any) => {
  const statusText = row.status === 1 ? '启用' : '禁用';
  
  // 模拟API调用
  setTimeout(() => {
    ElMessage.success(`${statusText}成功`);
  }, 500);
};

// 重置表单
const resetForm = () => {
  categoryForm.id = 0;
  categoryForm.name = '';
  categoryForm.code = '';
  categoryForm.description = '';
  categoryForm.sort = 0;
  categoryForm.status = 1;
};

// 提交表单
const submitForm = async () => {
  if (!categoryFormRef.value) return;
  
  await categoryFormRef.value.validate(async (valid) => {
    if (valid) {
      // 模拟API调用
      setTimeout(() => {
        if (categoryForm.id === 0) {
          // 新增
          const newCategory = {
            ...categoryForm,
            id: categoryList.value.length + 1,
            createTime: new Date().toLocaleString()
          };
          categoryList.value.unshift(newCategory);
          total.value++;
          ElMessage.success('新增成功');
        } else {
          // 更新
          const index = categoryList.value.findIndex(item => item.id === categoryForm.id);
          if (index !== -1) {
            Object.assign(categoryList.value[index], categoryForm);
            ElMessage.success('更新成功');
          }
        }
        
        dialogVisible.value = false;
      }, 500);
    }
  });
};

// 分页大小变更
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  fetchCategoryList();
};

// 页码变更
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  fetchCategoryList();
};

onMounted(() => {
  fetchCategoryList();
});
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 